package cn.jhc.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

/**
 * Servlet Filter implementation class StudentFilter
 */
@WebFilter(filterName = "/StudentFilter", urlPatterns = "/user/*")
public class StudentFilter implements Filter {
	private static final Logger LOGGER = Logger.getLogger(StudentFilter.class.getName());
    /**
     * Default constructor. 
     */
    public StudentFilter() {
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		LOGGER.info("student 释放过滤器");
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		LOGGER.info("student 过滤器");
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)resp;
		
		if (isFilter(request)) {
			HttpSession session = request.getSession(false);
			if (session == null || session.getAttribute("role") == null || !session.getAttribute("role").equals("1")) {
				response.sendRedirect(request.getContextPath() + "/user/index.jsp");
				return;
			}
		}
		chain.doFilter(req, resp);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		LOGGER.info("student 启动过滤器");
	}
	
	public boolean isFilter(HttpServletRequest request){
		String servletPath = request.getServletPath();
		if (servletPath.startsWith("/user/student/")) {
			return true;
		}
		return false;
	}
}
